package eightDataType.mStr;

import java.io.UnsupportedEncodingException;

/**
 * @author Ajie
 * @date 4/16/21
 * @function  java使用的编码是utf-8还是utf-16.
 *
 * utf-8 1-4字节
 * utf-16 1-2字节。
 *
 * JVM之内：当运行java字节码时，读入到内存里的字符或者字符串都用char或char[]表示，而char是采用utf-16的
 * 但不是真正的utf-16，为什么这样说? char在java里一直是16位的也就是说只能表示带utf-16的0x0000-0xFFFF(BMP
 * basic multilingual plane)为止，当对于超过16位的utf-16字符来说(比如表情符号)就需要多个char了
 * ————————————————
 *
 * String.length 表示  String 中 final char value[]; 的 value.length;
 *
 * Java String 类支持任意编码方式转换，其中就包括 UTF-8 编码：
 *  byte[] bytesUtf8 = a.getBytes("utf-8");//encode  e4 b8 ad
 *  byte[] bytesUtf16 = a.getBytes("utf-16");//encode  fe ff 4e 2d
 */
public class StringUtf_8_16 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //java编码存在两方面内容：JVM之外和JVM之内

//        char ch1 ='😁';//too manay char in char
        char ch2 ='哈';

        String a = "中";
        System.out.println(a);
        System.out.println("str.length: "+a.length());
        System.out.println("str.toCharArray().length: "+a.toCharArray().length); //1
        byte[] originBytes = a.getBytes();
        for (byte origin:originBytes) {
            System.out.print(Integer.toHexString(Byte.toUnsignedInt(origin)));
            System.out.print(" ");
        }


        System.out.println("\n");
        byte[] bytesUtf8 = a.getBytes("utf-8");//encode  e4 b8 ad
        System.out.println("utf-8.length: "+bytesUtf8.length);// 3
        for (byte b:bytesUtf8) {
            System.out.print(Integer.toHexString(Byte.toUnsignedInt(b)));
            System.out.print(" ");
        }

        System.out.println("\n");
        byte[] bytesUtf16 = a.getBytes("utf-16");//encode  fe ff 4e 2d    ,fe ff 字节序标志
        System.out.println("utf-16.length: "+bytesUtf16.length);// 4
        for (byte b:bytesUtf16) {
            System.out.print(Integer.toHexString(Byte.toUnsignedInt(b)));
            System.out.print(" ");
        }


        System.out.println("\n");

        System.out.println("😁 length:"+"😁".length());//emoji  站用2个char
        System.out.println("中 length:"+"中".length());//emoji  站用2个char


    }
}
